package com.zjlp.im.netty.manager;

import com.zjlp.im.netty.bean.UserSessionBean;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Created by Administrator on 2016/11/2.
 */
public class SessionManager {

    private Map<String, UserSessionBean> userSession = new ConcurrentHashMap<>();

    private SessionManager() {
    }

    public static SessionManager getInstance() {
        return SessionManagerInstance.sessionManager;
    }

    private static class SessionManagerInstance {
        private static SessionManager sessionManager = new SessionManager();
    }

    public void addUserSession(String user, NioSocketChannel socketChannel) {
        UserSessionBean userSessionBean = new UserSessionBean();
        userSessionBean.setUsername(user);
        userSessionBean.setCid(socketChannel.id().toString());
        userSessionBean.setSocketChannel(socketChannel);
        userSession.put(user, userSessionBean);
        System.out.println("用户" + user + "添加入队列成功！当前队列总人数是" + userSession.size());
    }

    public void removeUserSessionByUser(String user) {
        if (userSession.isEmpty()) {
            System.out.println("暂无用户列表信息");
        } else {
            if (userSession.containsKey(user)) {
                userSession.remove(user);
            }
        }
    }

    public void removeUserSessionByCid(String cid) {
        if (userSession.isEmpty()) {
            System.out.println("暂无用户列表信息");
        } else {
            Set<String> userKeys = userSession.keySet();
            for (String user : userKeys) {
                UserSessionBean userSessionBean = userSession.get(user);
                if (userSessionBean.getCid().equals(cid)) {
                    userSession.remove(user);
                    System.out.println("客户端用户【" + user + "】的连接被关闭!当前线上总人数是 "+ userSession.size());
                    break;
                }
            }
        }
    }

    /**
     * 获取客户端连接的通道
     *
     * @param user
     * @return
     */
    public NioSocketChannel getUserSession(String user) {
        if (userSession.isEmpty()) {
            System.out.println("暂无用户列表信息");
            return null;
        } else {
            UserSessionBean userSessionBean = userSession.get(user);
            if (null != userSessionBean) {
                return userSessionBean.getSocketChannel();
            } else {
                return null;
            }
        }

    }

}
